<template>
  <div class="orderInfo">
    <div class="btns">
      <div>订单详情</div>
      <div>
        <el-button icon="CircleClose" size="large" @click="doClose">关闭</el-button>
        <!-- <el-button color="#F95505" icon="MapLocation" size="large" @click="toUpdataTakeGoodsInfo">修改收货信息</el-button> -->
        <el-button v-if="orderInfo.orderStatus === 1" color="#F95505" icon="Position" size="large" @click="sendShow = true">发货</el-button>
        <!-- <el-button type="primary" icon="ChatLineSquare" size="large" @click="toAddNote">添加备注</el-button> -->
      </div>
    </div>
    <div class="content">
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Tickets /></el-icon>
          <span class="title">订单信息</span>
        </template>
        <template #default>
          <div class="info">
            <div><span>订单编号：</span><span>{{ orderInfo.orderCode }}</span></div>
            <div>
              <span>订单状态：</span>
              <el-tag v-if="orderInfo.orderStatus === 0" type="info">待付款</el-tag>
              <el-tag v-if="orderInfo.orderStatus === 1" type="warning">待发货</el-tag>
              <el-tag v-if="orderInfo.orderStatus === 2">已发货</el-tag>
              <el-tag v-if="orderInfo.orderStatus === 3" type="success">已完成</el-tag>
              <el-tag v-if="orderInfo.orderStatus=== 4" type="danger">已关闭</el-tag>
            </div>
            <div>
              <span>订单来源：</span>
              <span v-if="orderInfo.sourceType === 0">APP</span>
              <span v-if="orderInfo.sourceType === 1">小程序</span>
              <span v-if="orderInfo.sourceType === 2">后台</span>
            </div>
            <div>
              <span>订单类型：</span>
              <span>{{ orderInfo.orderType ? '加盟订单' : '正常订单' }}</span>
            </div>
            <div>
              <span>支付方式：</span>
              <span v-if="orderInfo.payType === 0">未支付</span>
              <span v-if="orderInfo.payType === 1">支付宝</span>
              <span v-if="orderInfo.payType === 2">微信</span>
            </div>
            <div><span>付款状态：</span><span>{{ orderInfo.payStatus ? '已付款' : '未付款' }}</span></div>
            <div><span>下单时间：</span><span>{{ $date(orderInfo.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span></div>
            <div v-if="orderInfo.note" style="color: #F95505;"><el-icon><WarningFilled /></el-icon><span>订单备注：</span><span>{{ orderInfo.note }}</span></div>
            <div v-if="orderInfo.buyerNote" style="color: #F95505;"><el-icon><WarningFilled /></el-icon><span>买家备注：</span><span>{{ orderInfo.buyerNote }}</span></div>
          </div>
        </template>
      </el-card>
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Van /></el-icon>
          <span class="title">物流信息</span>
        </template>
        <template #default>
          <el-table :data="orderInfo.deliveryList" border>
            <el-table-column label="快递单号" prop="deliveryCode" align="center">
              <template #default="{row}">
                <el-button type="primary" link @click="toViewLogisticsLog(row.deliveryCode, true)">{{row.deliveryCode}}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="快递公司" prop="deliveryCompany" align="center"></el-table-column>
            <el-table-column label="配送方式" prop="deliveryType" align="center">
              <template #default="{row}">
                <span v-if="row.deliveryType === '0'">无需发货</span>
                <span v-if="row.deliveryType === '1'">物流发货</span>
                <span v-if="row.deliveryType === '2'">门店配送</span>
                <span v-if="row.deliveryType === '3'">到店自提</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-card>
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Guide /></el-icon>
          <span class="title">收货人信息及地址</span>
        </template>
        <template #default>
          <div class="info">
            <div><span>收货人姓名：</span><span>{{ consigneeInfo.name }}</span></div>
            <div><span>收货人电话：</span><span>{{ consigneeInfo.phone }}</span></div>
            <div><span>收货人地址：</span><span>{{ consigneeInfo.address }}</span></div>
          </div>
        </template>
      </el-card>
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Goods /></el-icon>
          <span class="title">商品信息</span>
        </template>
        <template #default>
          <el-table :data="goodsList" border>
            <el-table-column label="商品图片" prop="value1" align="center">
              <template #default="{row}">
                <div class="img-cell">
                  <el-image :src="row.pic + '?x-oss-process=image/resize,m_fill,h_40,w_40'" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name" header-align="center"></el-table-column>
            <el-table-column label="销售单价" prop="salePrice" align="center"></el-table-column>
            <el-table-column label="促销优惠金额" prop="promotionAmount" align="center"></el-table-column>
            <el-table-column label="点数抵扣金额" prop="pointAmount" align="center"></el-table-column>
            <el-table-column label="优惠券抵扣金额" prop="couponAmount" align="center"></el-table-column>
            <el-table-column label="后台调整折扣金额" prop="discountAmount" align="center"></el-table-column>
            <el-table-column label="购买数量" prop="quantity" align="center"></el-table-column>
            <el-table-column label="小计" prop="value9" align="center">
              <template #default="{row}">
                <span>{{ getTotalPrice(row) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-card>
      <el-card shadow="never">
        <template #header>
          <el-icon color="#ffffff"><Coin /></el-icon>
          <span class="title">费用信息</span>
        </template>
        <template #default>
          <el-table :data="costData" border>
            <el-table-column label="商品总额" prop="totalAmount" align="center"></el-table-column>
            <el-table-column label="促销优惠金额" prop="promotionAmount" align="center"></el-table-column>
            <el-table-column label="点数抵扣金额" prop="pointAmount" align="center"></el-table-column>
            <el-table-column label="优惠券抵扣金额" prop="couponAmount" align="center"></el-table-column>
            <el-table-column label="后台调整折扣金额" prop="discountAmount" align="center"></el-table-column>
            <el-table-column label="运费" prop="freightAmount" align="center"></el-table-column>
            <el-table-column label="应付金额" prop="payAmount" align="center"></el-table-column>
          </el-table>
        </template>
      </el-card>
    </div>

    <!-- 发货弹窗 -->
    <el-dialog v-model="sendShow" title="订单发货" top="10vh" width="40%" center draggable @close="resetForm">
      <el-form :model="sendGoodsForm">
        <el-form-item label="发货地址:">
          <span>{{ sendGoodsForm.address }}</span>
        </el-form-item>
        <el-form-item label="发货方式:">
          <el-radio-group v-model="sendGoodsForm.deliveryType" @change="sendGoodsForm.deliveryItemList = []">
            <el-radio label="0">无需发货</el-radio>
            <el-radio label="1">物流发货</el-radio>
            <el-radio label="2">门店配送</el-radio>
            <el-radio label="3">到店自提</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快递单号:">
          <el-button type="primary" icon="Plus" @click="doLogisticsInfo(true)">添加快递单号</el-button>
          <el-table :data="sendGoodsForm.deliveryItemList" border>
            <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
            <el-table-column label="快递单号" prop="deliveryCode" align="center">
              <template #default="{row}">
                <el-input v-model="row.deliveryCode" placeholder="请输入快递单号" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="物流公司" prop="deliveryCompany" align="center">
              <template #default="{row}">
                <el-input v-model="row.deliveryCompany" placeholder="请输入物流公司" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="{$index}">
                <el-button type="danger" icon="Delete" link @click="doLogisticsInfo(false, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSendGoods">发货</el-button>
        <el-button size="default" @click="sendShow = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 查看物流弹窗 -->
    <el-dialog v-model="logisticsShow" :title="title" top="10vh" width="50%" center draggable>
      <el-timeline>
        <el-timeline-item 
          v-for="(item, index) in logistics" 
          :key="index" 
          :timestamp="item.desc" 
          icon="Check" 
          color="#67C23A">
          {{ $date(item.time).format('YYYY-MM-DD HH:mm:ss') }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 修改收货人信息 -->
    <el-dialog v-model="takeGoodsShow" title="收货人信息" label-position="right" top="10vh" width="40%" center draggable>
      <el-form :model="takeGoodsForm" label-width="90px">
        <el-form-item label="收货人信息">
          <el-select v-model="takeGoodsForm.receiveId" placeholder="请选择收货人信息" style="width: 100%;">
            <el-option v-for="item in addresses" :key="item.id" :label="item.name + ' / ' + item.phone + ' / ' + item.fullName.replace(/\//g,'')" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doUpdateTakeGoodsInfo">保存</el-button>
        <el-button size="default" @click="takeGoodsShow = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="orderInfo">
  import { 
    getOrderInfoApi, 
    getSendGoodsAddressApi, 
    giveOrderSendGoodsApi, 
    getOrderInGoodsInfoApi, 
    getOrderLogisticsApi, 
    saveOrderNoteApi, 
    getAddressListApi, 
    updateAddressInfApi 
  } from '@/api/api'
  import { ref, getCurrentInstance, watch } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const emits = defineEmits(['close'])

  // 定义父组件传入的值
  const props = defineProps({
    orderId: {
      type: String,
      default: '',
      required: true
    }
  })
  
  let sendShow = ref(false)
  let logisticsShow = ref(false)
  let takeGoodsShow = ref(false)
  let title = ref('')
  let addresses = ref([])
  let logistics = ref([])
  let goodsList = ref([])
  let costData = ref([])
  let sendGoodsForm = ref({
    orderId: '',
    deliveryType: '1',
    deliveryItemList: [],
    address: ''
  })
  let takeGoodsForm = ref({
    orderId: '',
    receiveId: ''
  })
  let orderInfo = ref({
    orderCode: '',
    orderStatus: '',
    sourceType: '',
    orderType: '',
    payType: '',
    payStatus: '',
    createdTime: '',
    note: '',
    deliveryList: []
  })
  let consigneeInfo = ref({
    name: '',
    phone: '',
    address: ''
  })

  watch(() => props.orderId, (newVal) => {
    sendGoodsForm.value.orderId = props.orderId
    takeGoodsForm.value.orderId = props.orderId
    loadOrderInfo()
    loadOrderAddress()
    loadOrderGoodsInfo()
  }, {
    immediate: true // 立即监听
  })

  // 获取订单信息
  function loadOrderInfo() {
    getOrderInfoApi(props.orderId).then(res => {
      if(res.code === '200') {
        orderInfo.value = res.data
        costData.value = [{
          totalAmount: res.data.totalAmount,
          promotionAmount: res.data.promotionAmount,
          pointAmount: res.data.pointAmount,
          couponAmount: res.data.couponAmount,
          discountAmount: res.data.discountAmount,
          freightAmount: res.data.freightAmount,
          payAmount: res.data.payAmount
        }]
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 获取收货人信息及地址
  function loadOrderAddress() {
    getSendGoodsAddressApi(props.orderId).then(res => {
      if(res.code === '200') {
        consigneeInfo.value = {name: res.data.name, phone: res.data.phone, address: res.data.fullName.replace(/\//g,'') + res.data.detailAddress}
        sendGoodsForm.value.address = consigneeInfo.value.address
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 查询商品信息
  function loadOrderGoodsInfo() {
    getOrderInGoodsInfoApi(props.orderId).then(res => {
      if(res.code === '200') {
        goodsList.value = res.data
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 获取商品小计
  function getTotalPrice(e) {
    return parseInt(e.quantity) * e.salePrice - e.promotionAmount - e.pointAmount - e.couponAmount - e.discountAmount
  }

  // 执行发货
  function doSendGoods() {
    if(sendGoodsForm.value.deliveryItemList.length === 0) {
      currentThis.$message.error('请添加快递单号')
      return
    }
    for (let i = 0; i < sendGoodsForm.value.deliveryItemList.length; i++) {
      let itemData = sendGoodsForm.value.deliveryItemList[i]
      if(!itemData.deliveryCode) {
        currentThis.$message.error('请输入快递单号')
        return
      }
      if(!itemData.deliveryCompany) {
        currentThis.$message.error('请输入物流公司')
        return
      }
    }
    currentThis.$messageBox.confirm('确认发货吗？').then(() => {
      const loading = currentThis.$loading('正在处理，请耐心等待')
      giveOrderSendGoodsApi(sendGoodsForm.value).then(res => {
        loading.close()
        if(res.code === '200') {
          loadOrderInfo()
          loadOrderAddress()
          sendShow.value = false
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }
  // 添加快递单号
  function doLogisticsInfo(e, index) {
    if(e) {
      sendGoodsForm.value.deliveryItemList.push({deliveryCode: '', deliveryCompany: ''})
    } else {
      sendGoodsForm.value.deliveryItemList.splice(index, 1)
    }
  }
  
  // 点击添加备注按钮执行
  function toAddNote() {
    currentThis.$messageBox.prompt('卖家备注', '确认保存吗？').then(({value}) => {
      const loading = currentThis.$loading('正在处理，请耐心等待')
      let formData = new FormData() 
      formData.append('orderId', props.orderId)
      formData.append('remark', value)
      saveOrderNoteApi(formData).then(res => {
        loading.close()
        if(res.code === '200') {
          loadOrderInfo()
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  function toViewLogisticsLog(deliveryCode, e) {
    title.value = e ? '物流信息' : '订单日志'
    if(e) {
      getOrderLogisticsApi(deliveryCode).then(res => {
        if(res.code === '200') {
          logistics.value = res.data.data.logisticsTraceDetails
          logisticsShow.value = true
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }
  }

  function toUpdataTakeGoodsInfo() {
    getAddressListApi().then(res => {
      if(res.code === '200') {
        addresses.value = res.data
        takeGoodsShow.value = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  function doUpdateTakeGoodsInfo() {
    currentThis.$messageBox.confirm('确认修改吗？').then(() => {
      const loading = currentThis.$loading('正在处理，请耐心等待')
      updateAddressInfApi(takeGoodsForm.value).then(res => {
        loading.close()
        if(res.code === '200') {
          loadOrderAddress()
          takeGoodsShow.value = false
          currentThis.$message.success(res.message)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  function doClose() {
    emits('close')
  }

  function resetForm() {
    sendGoodsForm.value.deliveryType = '1'
    sendGoodsForm.value.deliveryItemList = []
  }
</script>

<style lang="less" scoped>
.orderInfo{
  padding: 0 80px;
  .btns{
    height: 8vh;
    display: flex;
    justify-content: space-between;
    align-items: center;
    >div{
      width: 50%;
      &:first-child{
        font-size: 25px;
        font-weight: bold;
      }
      &:last-child{
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  .content{
    height: 92vh;
    overflow: hidden auto;
    :deep(.el-card){
      margin-bottom: 15px;
      .el-card__header{
        display: flex;
        align-items: center;
        background: #3BB9F1;
        .el-icon{
          margin-right: 5px;
        }
        .title{
          color: #ffffff;
        }
      }
      .el-card__body{
        .info{
          display: flex;
          flex-wrap: wrap;
          line-height: 50px;
          >div{
            width: 33.3%;
            color: #333333;
            font-size: 14px;
            display: flex;
            align-items: center;
          }
        }
        .el-table{
          margin-top: 10px;
          .img-cell{
            display: flex;
            justify-content: center;
            align-items: center;
            .el-image{
              width: 40px; 
              height: 40px;
              border-radius: 5px;
            }
          }
        }
      }
    }
  }
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 500px;
      overflow: hidden auto;
    }
    .el-table{
      margin-top: 10px;
    }
  }
}
</style>